<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="地块编码" prop="plotCode">
              <el-input v-model="queryParams.plotCode" placeholder="请输入地块编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="投保面积" prop="insuredArea">
              <el-input v-model="queryParams.insuredArea" placeholder="请输入投保面积" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="实测面积" prop="measuredArea">
              <el-input v-model="queryParams.measuredArea" placeholder="请输入实测面积" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="农户id" prop="farmerId">
              <el-input v-model="queryParams.farmerId" placeholder="请输入农户id" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->



            <el-form-item label="经度坐标" prop="latitude">
              <el-input v-model="queryParams.latitude" placeholder="请输入经度坐标" clearable @keyup.enter="handleQuery"  />
            </el-form-item>
            <el-form-item label="纬度坐标" prop="longitude">
              <el-input v-model="queryParams.longitude" placeholder="请输入纬度坐标" clearable @keyup.enter="handleQuery" />
            </el-form-item>



            <!-- <el-form-item label="经度坐标" prop="latitude">
              <el-input v-model="queryParams.latitude" placeholder="请输入经度坐标" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="纬度坐标" prop="longitude">
              <el-input v-model="queryParams.longitude" placeholder="请输入纬度坐标" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->






            <el-form-item label="市" prop="city">
              <el-select v-model="queryParams.city" placeholder="请选择市" @change="handleCityChange">
                <el-option v-for="city in cityOptions" :key="city.id" :label="city.name" :value="city.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="县" prop="districtCounty">
              <el-select v-model="queryParams.districtCounty" placeholder="请选择县">
                <el-option v-for="county in countyOptions" :key="county.id" :label="county.name" :value="county.name" />
              </el-select>
            </el-form-item>


            <el-form-item label="乡" prop="town">
              <el-input v-model="queryParams.town" placeholder="请输入乡" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="村" prop="village">
              <el-input v-model="queryParams.village" placeholder="请输入村" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['Nyt7PlotDetailInfo:Nyt7PlotDetailInfo:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['Nyt7PlotDetailInfo:Nyt7PlotDetailInfo:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['Nyt7PlotDetailInfo:Nyt7PlotDetailInfo:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['Nyt7PlotDetailInfo:Nyt7PlotDetailInfo:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="Nyt7PlotDetailInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" width="60">
          <template #default="scope">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="地块编码" align="center" prop="plotCode" />
        <el-table-column label="投保面积" align="center" prop="insuredArea" />
        <el-table-column label="实测面积" align="center" prop="measuredArea" />
        <el-table-column label="农户名" align="center" prop="farmerInsuranceInfoVo.farmerName" />
        <el-table-column label="确权状态" align="center" prop="confirmationStatus" />
        <el-table-column label="经度坐标" align="center" prop="latitude" />
        <el-table-column label="纬度坐标" align="center" prop="longitude" />
        <!-- <el-table-column label="区域边界" align="center" prop="regionBoundary" /> -->
        <el-table-column label="市" align="center" prop="city" />
        <el-table-column label="县" align="center" prop="districtCounty" />
        <el-table-column label="乡" align="center" prop="town" />
        <el-table-column label="村" align="center" prop="village" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">


             <!-- 地图按钮 -->
            <el-tooltip content="地图" placement="top">
              <el-button link type="primary" icon="MapLocation" @click="openMapWithScope(scope.row)"></el-button>
            </el-tooltip>


            <!-- 详情 -->
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['Nyt7PlotDetailInfo:Nyt7PlotDetailInfo:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['Nyt7PlotDetailInfo:Nyt7PlotDetailInfo:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['Nyt7PlotDetailInfo:Nyt7PlotDetailInfo:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>




    <!-- 添加或修改地块详细信息对话框 -->
<el-dialog :title="dialog.title" v-model="dialog.visible" width="850px" append-to-body>
  <el-form ref="Nyt7PlotDetailInfoFormRef" :model="form" :rules="rules" label-width="110px" :disabled="dialog.isView">
    <el-card class="mb-4">
      <template #header>
        <div class="card-header">
          <span class="title">地块基本信息</span>
        </div>
      </template>
      <el-row :gutter="20">;
        <el-col :span="12">
          <el-form-item label="地块编码" prop="plotCode">
            <el-input v-model="form.plotCode" placeholder="请输入地块编码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="投保面积" prop="insuredArea">
            <el-input v-model="form.insuredArea" placeholder="请输入投保面积" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实测面积" prop="measuredArea">
            <el-input v-model="form.measuredArea" placeholder="请输入实测面积" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="农户名" prop="farmerInsuranceInfoVo.farmerName">
            <el-autocomplete
              v-model="form.farmerInsuranceInfoVo.farmerName"
              :fetch-suggestions="debounce(queryEntitySearchFarmer, 300)"
              placeholder="请输入投保人名称"
              clearable
              :trigger-on-focus="true"
              @select="handleEntitySelectFarmer"
            >
              <template #default="{ item }">
                <div class="suggestion-item">
                  <div class="entity-name">{{ item.farmerInsuranceInfo.farmerName }}</div>
                  <div class="entity-info text-gray-400 text-sm">
                    <span>身份证号: {{ item.farmerInsuranceInfo.farmerIdCard }}</span>
                    <span class="ml-2">家庭成员: {{ item.farmerInsuranceInfo.familyMemberName }}</span>
                  </div>
                </div>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="确权状态" prop="confirmationStatus">
            <el-input v-model="form.confirmationStatus" placeholder="请输入确权状态" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="mb-4">
      <template #header>
        <div class="card-header">
          <span class="title">位置信息</span>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="经度坐标" prop="latitude">
            <el-input v-model="form.latitude" placeholder="请输入经度坐标" clearable>
              <template #append>
                <el-button @click="openMap">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度坐标" prop="longitude">
            <el-input v-model="form.longitude" placeholder="请输入纬度坐标" clearable>
              <template #append>
                <el-button @click="openMap">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="市" prop="city">
            <el-select v-model="form.city" placeholder="请选择市" @change="handleCityChange">
              <el-option v-for="city in cityOptions" :key="city.id" :label="city.name" :value="city.name" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="县" prop="districtCounty">
            <el-select v-model="form.districtCounty" placeholder="请选择县">
              <el-option v-for="county in countyOptions" :key="county.id" :label="county.name" :value="county.name" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="乡" prop="town">
            <el-input v-model="form.town" placeholder="请输入乡" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="村" prop="village">
            <el-input v-model="form.village" placeholder="请输入村" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button :loading="buttonLoading" type="primary" @click="submitForm" v-if="!dialog.isView">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </template>
</el-dialog>

<!-- 详情对话框 -->
<el-dialog :title="dialog.title" v-model="dialog.viewVisible" width="850px" append-to-body>
  <el-form ref="Nyt7PlotDetailInfoFormRef" :model="form" :rules="rules" label-width="110px" disabled>
    <el-card class="mb-4">
      <template #header>
        <div class="card-header">
          <span class="title">地块基本信息</span>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="地块编码" prop="plotCode">
            <el-input v-model="form.plotCode" placeholder="请输入地块编码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="投保面积" prop="insuredArea">
            <el-input v-model="form.insuredArea" placeholder="请输入投保面积" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实测面积" prop="measuredArea">
            <el-input v-model="form.measuredArea" placeholder="请输入实测面积" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="农户名" prop="farmerInsuranceInfoVo.farmerName">
            <el-input v-model="form.farmerInsuranceInfoVo.farmerName" placeholder="请输入农户名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="确权状态" prop="confirmationStatus">
            <el-input v-model="form.confirmationStatus" placeholder="请输入确权状态" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="mb-4">
      <template #header>
        <div class="card-header">
          <span class="title">位置信息</span>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="经度坐标" prop="latitude">
            <el-input v-model="form.latitude" placeholder="请输入经度坐标" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度坐标" prop="longitude">
            <el-input v-model="form.longitude" placeholder="请输入纬度坐标" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="市" prop="city">
            <el-input v-model="form.city" placeholder="请输入市" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="县" prop="districtCounty">
            <el-input v-model="form.districtCounty" placeholder="请输入县" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="乡" prop="town">
            <el-input v-model="form.town" placeholder="请输入乡" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="村" prop="village">
            <el-input v-model="form.village" placeholder="请输入村" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="cancel">返 回</el-button>
    </div>
  </template>
</el-dialog>




  </div>

   <!-- 地图确认提交-->
    <el-dialog title="选择位置" v-model="mapDialogVisible" width="80%" append-to-body>
      <MapModal  :key="mapModalKey" :initialPosition="initialPosition" @confirm="handleMapConfirm" />
    </el-dialog>


</template>

<script setup name="Nyt7PlotDetailInfo" lang="ts">
import { listNyt7PlotDetailInfo, getNyt7PlotDetailInfo, delNyt7PlotDetailInfo, addNyt7PlotDetailInfo, updateNyt7PlotDetailInfo, exportSelected } from '@/api/Nyt7PlotDetailInfo/Nyt7PlotDetailInfo';
import { Nyt7PlotDetailInfoVO, Nyt7PlotDetailInfoQuery, Nyt7PlotDetailInfoForm } from '@/api/Nyt7PlotDetailInfo/Nyt7PlotDetailInfo/types';
import MapModal from '@/views/map/baidumap/MapModal.vue';

//引入农户
import { listNyt7FarmerInsuranceInfo } from "@/api/Nyt7FarmerInsuranceInfo/Nyt7FarmerInsuranceInfo";
import { Nyt7FarmerInsuranceInfoVO } from '@/api/Nyt7FarmerInsuranceInfo/Nyt7FarmerInsuranceInfo/types';


//引入区域管理的API和类型
import { listNyt7RegionManagement } from '@/api/Nyt7RegionManagement/Nyt7RegionManagement';
import { Nyt7RegionManagementVO } from '@/api/Nyt7RegionManagement/Nyt7RegionManagement/types';
import { EntitySearchResult } from '@/api/Nyt7PolicyInsurance/Nyt7PolicyInsurance/types';
import { searchEntityFarmer } from '@/api/Nyt7PolicyInsurance/Nyt7PolicyInsurance';
import { truncate } from 'node:fs/promises';







const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const Nyt7PlotDetailInfoList = ref<Nyt7PlotDetailInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);


const queryFormRef = ref<ElFormInstance>();
const Nyt7PlotDetailInfoFormRef = ref<ElFormInstance>();


const mapDialogVisible = ref(false);
const selectedField = ref('');
const initialPosition = ref({ lng: 114.655716, lat: 38.050204 });
const mapModalKey = ref(0); // 添加 key 属性

// 声明和初始化 farmerInfoList
const farmerInfoList = ref<Nyt7FarmerInsuranceInfoVO[]>([]);


//dinghies区域管理数据和选项
const regionManagementList = ref<Nyt7RegionManagementVO[]>([]);
const cityOptions = ref<Nyt7RegionManagementVO[]>([]);
const countyOptions = ref<Nyt7RegionManagementVO[]>([]);

const farmerManagementList = ref<Nyt7FarmerInsuranceInfoVO[]>([]);
const farmerOptions = ref<Nyt7FarmerInsuranceInfoVO[]>([]);











const selectedRows = ref<Nyt7PlotDetailInfoVO[]>([]);






















const dialog = reactive<DialogOption>({
  visible: false,
  viewVisible: false,
  title: '',
  isView: false
});


const initFormData: Nyt7PlotDetailInfoForm = {
  farmerInsuranceInfoVo: {} as Nyt7FarmerInsuranceInfoVO,
  id: undefined,
  plotCode: undefined,
  insuredArea: undefined,
  measuredArea: undefined,
  farmerId: undefined,
  confirmationStatus: undefined,
  latitude: undefined,
  longitude: undefined,
  // regionBoundary: undefined,
  city: undefined,
  districtCounty: undefined,
  town: undefined,
  village: undefined
}
const data = reactive<PageData<Nyt7PlotDetailInfoForm, Nyt7PlotDetailInfoQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    plotCode: undefined,
    insuredArea: undefined,
    measuredArea: undefined,
    farmerId: undefined,
    confirmationStatus: undefined,
    latitude: undefined,
    longitude: undefined,
    // regionBoundary: undefined,
    city: undefined,
    districtCounty: undefined,
    town: undefined,
    village: undefined,
    farmerInsuranceInfoVo: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "id不能为空", trigger: "blur" }
    ],
    plotCode: [
      { required: true, message: "地块编码不能为空", trigger: "blur" }
    ],
    insuredArea: [
      { required: true, message: "投保面积不能为空", trigger: "blur" }
    ],
    measuredArea: [
      { required: true, message: "实测面积不能为空", trigger: "blur" }
    ],
    farmerId: [
      { required: true, message: "农户id不能为空", trigger: "blur" }
    ],
    confirmationStatus: [
      { required: true, message: "确权状态不能为空", trigger: "change" }
    ],
    latitude: [
      { required: true, message: "经度坐标不能为空", trigger: "blur" }
    ],
    longitude: [
      { required: true, message: "纬度坐标不能为空", trigger: "blur" }
    ],
    // regionBoundary: [
    //   { required: true, message: "区域边界不能为空", trigger: "blur" }
    // ],
    city: [
      { required: true, message: "市不能为空", trigger: "blur" }
    ],
    districtCounty: [
      { required: true, message: "县不能为空", trigger: "blur" }
    ],
    town: [
      { required: true, message: "乡不能为空", trigger: "blur" }
    ],
    village: [
      { required: true, message: "村不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询地块详细信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listNyt7PlotDetailInfo(queryParams.value);
  Nyt7PlotDetailInfoList.value = res.rows;
  console.log(Nyt7PlotDetailInfoList);
  total.value = res.total;
  loading.value = false;
}


/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  dialog.viewVisible = false;
}


/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  Nyt7PlotDetailInfoFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

// /** 多选框选中数据 */
// const handleSelectionChange = (selection: Nyt7PlotDetailInfoVO[]) => {
//   ids.value = selection.map(item => item.id);
//   single.value = selection.length != 1;
//   multiple.value = !selection.length;
// }







const handleSelectionChange = (selection: Nyt7PlotDetailInfoVO[]) => {
  ids.value = selection.map(item => item.id);
  selectedRows.value = selection; // 存储选中的数据行
  single.value = selection.length !== 1;
  multiple.value = selection.length === 0;
}















/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.isView = false;
  dialog.title = "添加地块详细信息";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: Nyt7PlotDetailInfoVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getNyt7PlotDetailInfo(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.isView = false;
  dialog.title = "修改地块详细信息";
}
/** 提交按钮 */
const submitForm = () => {
  Nyt7PlotDetailInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateNyt7PlotDetailInfo(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addNyt7PlotDetailInfo(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: Nyt7PlotDetailInfoVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除地块详细信息编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delNyt7PlotDetailInfo(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

// /** 导出按钮操作 */
// const handleExport = () => {
//   proxy?.download('Nyt7PlotDetailInfo/Nyt7PlotDetailInfo/export', {
//     ...queryParams.value
//   }, `Nyt7PlotDetailInfo_${new Date().getTime()}.xlsx`)
// }



const handleExport = () => {
  if (selectedRows.value.length > 0) {
    // 导出选中的数据
    exportSelectedRows(selectedRows.value);
  } else {
    // 导出所有数据
    proxy?.download('Nyt7PlotDetailInfo/Nyt7PlotDetailInfo/export', {
      ...queryParams.value
    }, `Nyt7PlotDetailInfo_${new Date().getTime()}.xlsx`);
  }
}

const exportSelectedRows = async (rows: Nyt7PlotDetailInfoVO[]) => {
  try {
    const response = await exportSelected(rows.map(row => row.id));
    const url = window.URL.createObjectURL(new Blob([response]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `Nyt7PlotDetailInfo_${new Date().getTime()}.xlsx`);
    document.body.appendChild(link);
    link.click();
  } catch (error) {
    console.error('导出选中的数据失败:', error);
    proxy?.$modal.msgError('导出选中的数据失败');
  }
}














// 修改 openMap 方法
const openMap = () => {
  // console.log('form:', form.value); // 添加调试信息
  if (form.value.latitude && form.value.longitude) {
    initialPosition.value = {
      lng: parseFloat(form.value.longitude),
      lat: parseFloat(form.value.latitude)
    };
  } else {
    initialPosition.value = { lng: 114.655716, lat: 38.050204 };
  }

//  // 关闭并重新打开地图弹窗以确保重新初始化
//   mapDialogVisible.value = false;
//   setTimeout(() => {
    //打开地图弹窗
  mapModalKey.value += 1;
  mapDialogVisible.value = true;
  // }, 100);

};

const handleMapConfirm = (position: { lng: number, lat: number }) => {
  form.value.latitude = position.lat.toString();
  form.value.longitude = position.lng.toString();
  mapDialogVisible.value = false;
};



// 修改 openMap 方法，使其接受一个参数
const openMapWithScope = (row: Nyt7PlotDetailInfoVO) => {
  if (row.latitude && row.longitude) {
    initialPosition.value = {
      lng: parseFloat(row.longitude),
      lat: parseFloat(row.latitude)
    };
  } else {
    initialPosition.value = { lng: 114.655716, lat: 38.050204 };
  }

  // 关闭并重新打开地图弹窗以确保重新初始化
  mapDialogVisible.value = false;
  setTimeout(() => {
    mapModalKey.value += 1;
    mapDialogVisible.value = true;
  }, 100);
};




//获取区域管理数据的方法
const getRegionManagementList = async () => {
  const res = await listNyt7RegionManagement();
  regionManagementList.value = res.data;
  cityOptions.value = regionManagementList.value.filter(item => item.pid === 182754); // 假设parentId为0的是市
};

//处理市的选择变化
const handleCityChange = (cityName: string) => {
  const selectedCity = cityOptions.value.find(city => city.name === cityName);
  if (selectedCity) {
    countyOptions.value = regionManagementList.value.filter(item => item.pid === selectedCity.id);
  } else {
    countyOptions.value = [];
  }
};

// 防抖函数
const debounce = (fn: Function, delay: number) => {
  let timer: NodeJS.Timeout | null = null;
  return (...args: any[]) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(null, args);
    }, delay);
  };
};
// 实体搜索建议
const queryEntitySearchFarmer = async (queryString: string, cb: (data: EntitySearchResult[]) => void) => {
  if (queryString.length < 1) {
    cb([]);
    return;
  }

  try {
    const res = await searchEntityFarmer(queryString);

    const suggestions = res.data || [];
    cb(suggestions);
  } catch (error) {
    console.error('获取搜索建议失败:', error);
    proxy?.$modal.msgError('获取搜索建议失败');
    cb([]);
  }
};

// 处理实体选择
const handleEntitySelectFarmer = (item: EntitySearchResult) => {
  form.value.farmerId = item.farmerInsuranceInfo.id;
  form.value.farmerInsuranceInfoVo.farmerName = item.farmerInsuranceInfo.farmerName;
};


/** 详情按钮操作 */
const handleView = async (row?: Nyt7PlotDetailInfoVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getNyt7PlotDetailInfo(_id);
  Object.assign(form.value, res.data);
  dialog.viewVisible = true;
  dialog.isView = true;
  dialog.title = "地块详细信息详情";
}



onMounted(() => {
  getList();
  //在 onMounted 生命周期中调用获取区域管理数据的方法：
  getRegionManagementList();
});
</script>
